import React, {forwardRef, useEffect, useImperativeHandle, useState,} from 'react';
import {Select} from 'antd';
import {GSelectProps} from './SelectProps';
import {useDebounceFn} from "@ant-design/pro-components";
import {request} from "../Request";

export const GSelect = forwardRef((props: GSelectProps<any>, ref: any) => {
  const [options, setOptions] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  const {run: onSearch} = useDebounceFn((text: string): Promise<any> => {
    if (!props.url) {
      return Promise.resolve();
    }

    const queryParameter: any = {
      pageSize: props.maxSize || 10,
      pageIndex: 0,
      sort: props.sort,
      ...props?.filter
    };

    if (props?.showSearch && text !== '') {
      queryParameter[props.fieldNames?.label || 'nameLike'] = '%' + text + '%'
    }

    return request(props.url, {
      method: props.method || 'get',
      requestData: queryParameter,
      loadingSetter: setLoading,
      errMsg: '获取数据错误'
    }).then((resp: any) => {
      const data = resp.content || resp;
      setOptions(data);
      props?.onDataLoaded?.(data);
    });
  });

  useImperativeHandle(ref, () => ({
    loadData: () => {
      onSearch('');
    },
  }));

  useEffect(() => {
    if (props.autoload !== 'false') {
      onSearch('');
    }
  }, [props.url]);

  return (
    <Select
      style={{minWidth: 200}}
      fieldNames={{
        label: 'name',
        value: 'id',
      }}
      options={options}
      loading={loading}
      onSearch={props.showSearch ? onSearch : undefined}
      {...props}
    />
  );
});
